import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split #继承划分训练集和测试机
from sklearn.neighbors import KNeighborsClassifier  #K近邻
import matplotlib.pyplot as plt
from collections import Counter     #用于统计分类正确的样本数
from sklearn.preprocessing import StandardScaler#导入用于归一化的包
from sklearn.model_selection import cross_val_score#k折

AF_input_frame=pd.read_excel('pre_treatment_data.xlsx',sheet_name='AF_input')
nonAF_input_frame=pd.read_excel('pre_treatment_data.xlsx',sheet_name='nonAF_input')
AF_label_frame=pd.read_excel('pre_treatment_data.xlsx',sheet_name='AF_label')
nonAF_label_frame=pd.read_excel('pre_treatment_data.xlsx',sheet_name='nonAF_label')

AF_input=AF_input_frame.to_numpy()
nonAF_input=nonAF_input_frame.to_numpy()
AF_label=AF_label_frame.to_numpy()
nonAF_label=nonAF_label_frame.to_numpy()

AF_label=AF_label.flatten()
nonAF_label=nonAF_label.flatten()

print(AF_input.shape,nonAF_input.shape,AF_label.shape,nonAF_label.shape)

raw_x=np.concatenate([AF_input,nonAF_input])
raw_y=np.concatenate([AF_label[0:],nonAF_label[0:]])

print(raw_x.shape,raw_y.shape)

index=[] #用于保存每次测验的划分比
acc=[] #保存准确率
for i in range(1,6):
    index.append(0.1*i)#测试计划分的比例
    x_train,x_test,y_train,y_test=train_test_split(raw_x,raw_y,test_size=0.1*i,random_state=0)
    #创建KNN对象，近邻K值统一为10
    #print(x_train.shape,x_test.shape,y_train.shape,y_test.shape)
    model=KNeighborsClassifier(n_neighbors=10)
    model.fit(x_train,y_train)#模型训练
    y_pred=model.predict(x_test)#预测
    #用分类正确的样本得到准确率acc
    acc.append(Counter(y_pred==y_test)[True]/x_test.shape[0])
    #绘制“划分比例---准确度”曲线
    plt.plot(index,acc)
    plt.show()

raw_x=np.concatenate([AF_input,nonAF_input])
print(raw_x.shape)
raw_y=np.concatenate([AF_label[0:],nonAF_label[0:]])
acc_list=[]

ss=StandardScaler()
raw_x=ss.fit_transform(raw_x)

k=10
m=400
m_min=400
m_max=600
m_interval=20
index=np.array(range(m_min,m_max,m_interval))
for i in range(m_min,m_max+1,m_interval):
    model=KNeighborsClassifier(n_neighbors=i,weights='uniform')
    acc=cross_val_score(model,raw_x,raw_y,cv=k,scoring="accuracy")
    mean_acc=np.array(acc).mean()
    print(mean_acc)
    acc_list.append(mean_acc)
plt.plot(np.array(range(400,601,20)),np.array(acc_list))
plt.xlim(400,600)
plt.show()